package com.sgb.kjwl.viewmodel.transport;

import android.app.Application;
import android.content.Context;
import android.text.TextUtils;

import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.google.gson.reflect.TypeToken;

import com.sgb.kjwl.api.GsonManager;
import com.swgk.core.base.api.ICallBack;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.transport.CarFilterEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.transport.GoodsSourceLocationEntity;
import com.sgb.kjwl.model.entity.transport.MapCarEntity;
import com.sgb.kjwl.model.entity.transport.MapCarPositionEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.utils.AddressHelper;
import com.sgb.kjwl.utils.LocationUtil;
import com.sgb.kjwl.utils.NumberUtil;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapCarrierFramgentModel extends AndroidViewModel {
    public MutableLiveData<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>> ldAddress = new MutableLiveData<>();
    public MutableLiveData<MapCarPositionEntity> ldPosition = new MutableLiveData<>();
    public MutableLiveData<List<GoodsInfoTypeEntity3>> ldCarLen = new MutableLiveData<>();
    public MutableLiveData<List<GoodsInfoTypeEntity3>> ldCarType = new MutableLiveData<>();
    public MutableLiveData<CarFilterEntity> ldFilter = new MutableLiveData<>();
    public MutableLiveData<LatLng> ldLatLng = new MutableLiveData<>();
    public MutableLiveData<List<MapCarEntity>> ldCars = new MutableLiveData<>();
    // 一级联动数据
    private final List<AddressEntity> mProvinceList = new ArrayList<>();
    // 二级联动数据
    private final List<List<AddressEntity>> mCityList = new ArrayList<>();
    // 三级联动数据
    private final List<List<List<AddressEntity>>> mDistrictList = new ArrayList<>();
    //当前用户定位经纬度
    private double mLat;
    private double mLog;

    public MapCarrierFramgentModel(Application application) {
        super(application);
        ldFilter.setValue(new CarFilterEntity());
        //设置经纬度
        mLat = NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, "0"));
        mLog = NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "0"));
    }

    /**
     * 获取省市区地址
     */
    public void getAddressModel(Context context) {
        DialogHelper.showProgressDialog(context, "数据加载中...");
        AddressHelper.getInstance().getAllArea(new AddressHelper.AddressCallBack() {
            @Override
            public void initialData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
                DialogHelper.dismissProgressDialog();
                if (data != null) {
                    ldAddress.postValue(data);
                    initAddress(context, data);
                    //获取车辆信息
                    getCarTypeList();
                }
            }
        });
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    private void initAddress(Context context, List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> list) {
        //拷贝数据，保留原始数据
        String dataStr = GsonManager.getInstance().getGson().toJson(list);
        List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data = GsonManager.getInstance().getGson().fromJson(dataStr, new TypeToken<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>() {
        }.getType());
        //添加全国
        data.add(0, new AddressEntity("", "不限", "", "不限"));
        for (AddressEntity<List<AddressEntity<List<AddressEntity>>>> pro : data) {
            //一级列表
            mProvinceList.add(pro);
            //二级列表
            if (pro.getChildren() == null) {
                pro.setChildren(new ArrayList<>());
            }
            //添加全省
            if (pro.getChildren().size() > 1) {
                pro.getChildren().add(0, new AddressEntity("", "不限", "", "不限"));
            }
            List<AddressEntity> cityList = new ArrayList<>(pro.getChildren());
            mCityList.add(cityList);
            //三级列表
            List<List<AddressEntity>> areaList = new ArrayList<>();
            for (AddressEntity<List<AddressEntity>> area : pro.getChildren()) {
                if (area.getChildren() == null) {
                    area.setChildren(new ArrayList<>());
                }
                area.getChildren().add(0, new AddressEntity("", "不限", "", "不限"));
                areaList.add(area.getChildren());
            }
            mDistrictList.add(areaList);
        }
        //查找地址下标
        if (LocationUtil.isOpenLocation(context)) {
            String provinceName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.Province, "新疆");
            String cityName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.City, "乌鲁木齐");
            findPositionByAddress(provinceName, cityName, "");
        } else {
            findPositionByAddress("新疆", "乌鲁木齐", "");
        }
    }

    /**
     * 获取车辆类型
     */
    public void getCarTypeList() {
        NewAPIManager.getInstance().getLogisticsAPI().getCarTypeAndLen("").enqueue(new ICallBack<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
            @Override
            public void onSuccess(BaseEntity<List<GoodsInfoTypeEntity3>> data) {
                List<GoodsInfoTypeEntity3> carTypeList = data.getData() != null ? data.getData() : new ArrayList<>();
                List<GoodsInfoTypeEntity3> carLenList = new ArrayList<>();
                //添加全部车长数据
                for (GoodsInfoTypeEntity3 carType : carTypeList) {
                    if (carType.getCarLenList() == null) continue;
                    carLenList.addAll(carType.getCarLenList());
                }
                //添加车型不限时所有车长数据
                GoodsInfoTypeEntity3 type = new GoodsInfoTypeEntity3("", "不限");
                type.setCarLenList(carLenList);
                carTypeList.add(0, type);
                //添加子列表不限车长
                for (GoodsInfoTypeEntity3 carType : carTypeList) {
                    if (carType.getCarLenList() == null) {
                        carType.setCarLenList(new ArrayList<>());
                    }
                    GoodsInfoTypeEntity3 len = new GoodsInfoTypeEntity3("", "不限");
                    carType.getCarLenList().add(0, len);
                }
                //刷新车长与车型
                ldCarType.postValue(carTypeList);
                ldCarLen.postValue(carLenList);
            }
        });
    }

    //根据城市区域查询经纬度
    public void getLocation(Context context, String cityName, String areaName) {
        if (cityName.equals("不限")) {
            cityName = ldFilter.getValue().getSend().getProvinceName();
        }
        GeocodeSearch geocodeSearch = new GeocodeSearch(context);
        geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int code) {

            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int code) {
                if (code != 1000) return;
                if (geocodeResult != null && geocodeResult.getGeocodeAddressList() != null &&
                        geocodeResult.getGeocodeAddressList().size() > 0) {
                    GeocodeAddress geocodeAddress = geocodeResult.getGeocodeAddressList().get(0);
                    double latitude = geocodeAddress.getLatLonPoint().getLatitude();//纬度
                    double longitude = geocodeAddress.getLatLonPoint().getLongitude();//经度
                    //回调UI
                    ldLatLng.postValue(new LatLng(latitude, longitude));
                } else {
                    MToast.showToast(getApplication(), "地址名出错");
                }
            }
        });
        GeocodeQuery geocodeQuery = new GeocodeQuery(cityName + areaName, cityName);
        geocodeSearch.getFromLocationNameAsyn(geocodeQuery);
    }

    //根据经纬度查询城市区域
    public void getCityByLocation(Context context, double lat, double lon) {
        //通过经纬度获取位置信息
        GeocodeSearch geocodeSearch = new GeocodeSearch(context);
        // 第一个参数表示一个LatLng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        RegeocodeQuery query = new RegeocodeQuery(new LatLonPoint(lat, lon), 200, GeocodeSearch.AMAP);
        geocodeSearch.getFromLocationAsyn(query);
        //搜索位置信息
        geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult result, int code) {
                if (code != 1000) return;
                RegeocodeAddress address = result.getRegeocodeAddress();
                if (address != null) {
                    //查找到市
                    findPositionByAddress(address.getProvince(), address.getCity(), "");
                }
            }

            @Override
            public void onGeocodeSearched(GeocodeResult result, int code) {

            }
        });
    }

    /**
     * 通过地址查找下标
     */
    private void findPositionByAddress(String provinceName, String cityName, String districtName) {
        //创建发货地数据
        if (ldFilter.getValue().getSend() == null) {
            ldFilter.getValue().setSend(new GoodsSourceLocationEntity());
        }
        //省市区弹窗选中位置
        int proPos = 0, cityPos = 0, disPos = 0;
        //针对特殊省处理
        if (!TextUtils.isEmpty(provinceName)) {
            if (provinceName.contains("台湾")) {
                //针对特殊省处理
                provinceName = "台湾";
            } else if (provinceName.endsWith("市")) {
                //针对直辖市处理(适应接口)
                provinceName = provinceName.substring(0, provinceName.length() - 1);
            }
        }
        //查找省position
        for (AddressEntity entity : mProvinceList) {
            if (entity.getName().contains(provinceName)) {
                ldFilter.getValue().getSend().setProvinceNo(entity.getNo());
                ldFilter.getValue().getSend().setProvinceName(entity.getSimpleName());
                proPos = mProvinceList.indexOf(entity);
                break;
            }
        }
        //查找市position
        List<AddressEntity> cityList = mCityList.get(proPos);
        for (AddressEntity entity : cityList) {
            if (entity.getName().contains(cityName)) {
                ldFilter.getValue().getSend().setCityNo(entity.getNo());
                ldFilter.getValue().getSend().setCityName(entity.getSimpleName());
                cityPos = cityList.indexOf(entity);
                break;
            }
        }
        //查找区position
        if (districtName.endsWith("市") || districtName.endsWith("县") || districtName.endsWith("区")) {
            districtName = districtName.substring(0, districtName.length() - 1);
        }
        if (mDistrictList != null && mDistrictList.get(proPos).size() > 0) {
            List<AddressEntity> districtList = mDistrictList.get(proPos).get(cityPos);
            for (AddressEntity entity : districtList) {
                if (entity.getName().contains(districtName)) {
                    ldFilter.getValue().getSend().setAreaNo(entity.getNo());
                    ldFilter.getValue().getSend().setAreaName(entity.getSimpleName());
                    disPos = districtList.indexOf(entity);
                    break;
                }
            }
        }
        ldPosition.postValue(new MapCarPositionEntity(proPos, cityPos, disPos));
    }

    /**
     * 获取车辆列表
     */
    public void getCarList(Context context) {
        //判断筛选条件
        if (ldFilter.getValue() == null) return;
        Map<String, Object> map = new HashMap<>();
        //一次性加载50条
        map.put("page", 1);
        map.put("limit", 50);
        if (LocationUtil.isOpenLocation(context)) {
            map.put("isAuthorization", 1);
            //设置当前定位经纬度
            map.put("ipLongitude", mLog);
            map.put("ipLatitude", mLat);
        } else {
            map.put("isAuthorization", 0);
            map.put("cityNo", ldFilter.getValue().getSend().getCityNo());
        }
        //当前查找经纬度
        map.put("searchLongitude", ldFilter.getValue().getLongitude());
        map.put("searchLatitude", ldFilter.getValue().getLatitude());
        //发货地
        if (ldFilter.getValue().getSend() != null) {
            map.put("shipProvinceNo", ldFilter.getValue().getSend().getProvinceNo());
            map.put("shipCityNo", ldFilter.getValue().getSend().getCityNo());
            map.put("shipDistrictNo", ldFilter.getValue().getSend().getAreaNo());
        }
        //车长
        if (ldFilter.getValue().getCarLen() != null) {
            map.put("carLenNo", ldFilter.getValue().getCarLen().getNo());
        }
        //车辆类型
        if (ldFilter.getValue().getCarType() != null) {
            map.put("carTypeNo", ldFilter.getValue().getCarType().getNo());
        }
        //当前地图半径
        if (!TextUtils.isEmpty(ldFilter.getValue().getRadius())) {
            map.put("radius", ldFilter.getValue().getRadius());
        }
        DialogHelper.showProgressDialog(context, "数据获取中...").setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getLogisticsAPI().getMapFindCar(map).enqueue(new ICallBack<BaseEntity<List<MapCarEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<MapCarEntity>> data) {
                if (data.getData() == null) {
                    MToast.showToast(context, "没有更多车源了");
                    return;
                }
                //刷新数据，添加地图marker
                ldCars.postValue(data.getData());
            }

            @Override
            public void onFail() {
                MToast.showToast(context, "没有更多车源了");
            }
        });
    }

    public void getSearchCarList(Context context, String keyword) {
        //判断筛选条件
        if (ldFilter.getValue() == null) return;
        Map<String, Object> map = new HashMap<>();
        map.put("isIndexSearch", 1);
        map.put("keyWord", keyword);
        //一次性加载50条
        map.put("page", 1);
        map.put("limit", 50);
        if (LocationUtil.isOpenLocation(context)) {
            map.put("isAuthorization", 1);
            //设置当前定位经纬度
            map.put("ipLongitude", mLog);
            map.put("ipLatitude", mLat);
        } else {
            map.put("isAuthorization", 0);
            map.put("cityNo", ldFilter.getValue().getSend().getCityNo());
        }
        //当前查找经纬度
        map.put("searchLongitude", ldFilter.getValue().getLongitude());
        map.put("searchLatitude", ldFilter.getValue().getLatitude());
        //发货地
        if (ldFilter.getValue().getSend() != null) {
            map.put("shipProvinceNo", ldFilter.getValue().getSend().getProvinceNo());
            map.put("shipCityNo", ldFilter.getValue().getSend().getCityNo());
            map.put("shipDistrictNo", ldFilter.getValue().getSend().getAreaNo());
        }
        //车长
        if (ldFilter.getValue().getCarLen() != null) {
            map.put("carLenNo", ldFilter.getValue().getCarLen().getNo());
        }
        //车辆类型
        if (ldFilter.getValue().getCarType() != null) {
            map.put("carTypeNo", ldFilter.getValue().getCarType().getNo());
        }
        //当前地图半径
        if (!TextUtils.isEmpty(ldFilter.getValue().getRadius())) {
            map.put("radius", ldFilter.getValue().getRadius());
        }
        DialogHelper.showProgressDialog(context, "数据获取中...").setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getLogisticsAPI().getMapFindCar(map).enqueue(new ICallBack<BaseEntity<List<MapCarEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<MapCarEntity>> data) {
                if (data.getData() == null) {
                    MToast.showToast(context, "没有更多车源了");
                    return;
                }
                //刷新数据，添加地图marker
                ldCars.postValue(data.getData());
            }

            @Override
            public void onFail() {
                MToast.showToast(context, "没有更多车源了");
            }
        });
    }


}
